<template>
  <view>
    <block v-for="(user,index) in users" :key="index">
      <tui-collapse :index="index" :current="current" @click="detailUser(index)">
        <template v-slot:title>
          <tui-list-cell>
            <view>{{user.remark}}</view>
            <text class="tui-msg-content tui-flex-1">({{user._id}})</text>
            <tui-button
              type="primary"
              size="small"
              :stop="true"
              @click="remarkUserName(index)"
              style="margin-right:50upx;"
            >备注</tui-button>
          </tui-list-cell>
        </template>
        <template v-slot:content>
          <tui-list-view class="tui-list-view">
            <tui-list-cell v-for="(book,idk) in user.books" :key="idk" @click="detailBook(book)">
              <view class="tui-flex w-100">
                <view class="tui-flex-1">{{book.name}}</view>
                <view class="tui-msg-content">{{book.author}}</view>
              </view>
            </tui-list-cell>
          </tui-list-view>
        </template>
      </tui-collapse>
    </block>
    <uni-pagination :current="pageIndex+1" :pageSize="pageSize" :total="total" @change="goPage" />
    <tui-modal :show="showRemarkModal" @cancel="hideRemarkModal" :custom="true" :fadein="true">
      <view class="tui-modal-custom">
        <view class="tui-prompt-title">用户备注名称</view>
        <input
          placeholder="请输入用户备注名称"
          class="tui-input"
          v-model="remark"
          :focus="showRemarkModal"
          @confirm="submitRemark"
        />
        <tui-button
          type="primary"
          shape="circle"
          :disabled="!remark"
          :loading="remarkLoading"
          @click="submitRemark"
          size="small"
        >立即提交</tui-button>
      </view>
    </tui-modal>
    <tui-tips
      v-if="users.length == 0"
      :position="center"
      imgUrl="/static/images/toast/img_nodata.png"
    >暂无用户</tui-tips>
  </view>
</template>

<script>
import { mapState } from "vuex";
import uniPagination from "@/components/uni-pagination/uni-pagination.vue";
import tuiCollapse from "@/components/tui-collapse/tui-collapse.vue";
import tuiListView from "@/components/list-view/list-view.vue";
import tuiListCell from "@/components/list-cell/list-cell.vue";
import tuiButton from "@/components/button/button.vue";
import tuiModal from "@/components/modal/modal";
import tuiTips from "@/components/extend/tips/tips";

export default {
  components: {
    uniPagination,
    tuiCollapse,
    tuiListView,
    tuiListCell,
    tuiButton,
    tuiModal,
    tuiTips
  },
  data() {
    return {
      users: [],
      pageIndex: 0,
      pageSize: 10,
      current: -1,
      remark: "",
      showRemarkModal: false,
      remarkUserIndex: -1,
      total: 0,
      remarkLoading: false
    };
  },
  computed: mapState(["config"]),
  onLoad() {
    if (!this.config.admin) {
      this.tui.toast("您不是管理员！");
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000);
      return;
    }
    this.init();
  },
  methods: {
    init() {
      uni.showLoading({
        title: "加载中"
      });
      this.callFunc({
        name: "users",
        data: {
          pageIndex: this.pageIndex
        }
      })
        .then(res => {
          // console.log("res:", res);
          uni.hideLoading();
          if (res.errMsg == "cloud.callFunction:ok") {
            if (res.result.errMsg == "ok") {
              this.users = res.result.data.list;
              this.total = res.result.data.total;
            } else {
              this.tui.toast(res.result.errMsg);
            }
          } else {
            this.tui.toast(res.errMsg);
          }
        })
        .catch(err => {
          console.log("err:", err);
        });
    },
    detailUser(index) {
      if (this.current == index) {
        this.current = -1;
      } else {
        this.current = index;
      }
    },
    detailBook(book) {
      uni.navigateTo({
        url:
          "/pages/detail/detail?source_id=" +
          book.source_id +
          "&read_url=" +
          book.read_url
      });
    },
    remarkUserName(index) {
      this.showRemarkModal = true;
      this.remarkUserIndex = index;
    },
    hideRemarkModal() {
      this.showRemarkModal = false;
      this.remark = "";
      this.remarkUserIndex = -1;
      this.remarkLoading = false;
    },
    submitRemark() {
      if (this.remarkLoading) {
        return;
      }
      const remark = this.remark.trim();
      if (!remark) {
        this.tui.toast("不能输入空值");
        return;
      }
      if (this.remarkUserIndex < 0) {
        this.tui.toast("用户为空");
      }
      const remarkUser = this.users[this.remarkUserIndex];
      // console.log(remarkUser._id);

      this.remarkLoading = true;
      this.db
        .collection("users")
        .where({
          _id: remarkUser._id
        })
        .count()
        .then(res => {
          // console.log("res", res);
          if (res.errMsg == "collection.count:ok") {
            if (res.total > 0) {
              this.db
                .collection("users")
                .doc(remarkUser._id)
                .update({
                  data: {
                    remark: remark
                  }
                })
                .then(r => {
                  if (r.errMsg == "document.update:ok") {
                    this.tui.toast("设置成功");
                    this.users[this.remarkUserIndex].remark = remark;
                    this.hideRemarkModal();
                  } else {
                    this.tui.toast(r.errMsg);
                    this.remarkLoading = false;
                  }
                })
                .catch(e => {
                  this.remarkLoading = false;
                  console.error(e);
                });
            } else {
              this.db
                .collection("users")
                .add({
                  data: {
                    _id: remarkUser._id,
                    remark: remark
                  }
                })
                .then(r => {
                  // console.log("r", r);
                  if (r.errMsg == "collection.add:ok") {
                    this.tui.toast("设置成功");
                    this.users[this.remarkUserIndex].remark = remark;
                    this.hideRemarkModal();
                  } else {
                    this.tui.toast(r.errMsg);
                    this.remarkLoading = false;
                  }
                })
                .catch(e => {
                  this.remarkLoading = false;
                  console.error(e);
                });
            }
          } else {
            this.tui.toast(res.errMsg);
            this.remarkLoading = false;
          }
        })
        .catch(e => {
          this.remarkLoading = false;
          console.error(e);
        });
    },
    goPage({ type, current }) {
      // console.log(type, current);
      this.pageIndex = current - 1;
      this.$nextTick(this.init);
    }
  }
};
</script>

<style>
.tui-msg-content {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 26upx;
  line-height: 1;
  color: #9397a4;
}
.tui-modal-custom {
  text-align: center;
}
.tui-prompt-title {
  padding-bottom: 20rpx;
  font-size: 34rpx;
}
.tui-input {
  margin: 30rpx 40rpx;
  border-bottom: 1rpx solid #e6e6e6;
  padding-bottom: 20rpx;
  font-size: 32rpx;
}
</style>